package com.journey.org.ui.knowledge.gankio

import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import com.google.android.material.tabs.TabLayout
import com.journey.org.BR
import com.journey.org.R
import com.journey.org.databinding.FragmentGankMenuBinding
import com.journey.org.entity.GankMenuEntity
import com.journey.org.ui.knowledge.gankio.list.GankListFragment
import com.mvvmhabit.org.base.BaseFragment
import com.mvvmhabit.org.base.BaseFragmentPagerAdapter

/**
 * @Date: 2020/12/16 9:35
 * @Author:小妖
 * @Description: 干货文章分类
 */
class GankMenuFragment : BaseFragment<FragmentGankMenuBinding, GankMenuViewModel>() {

    private val mFragment = ArrayList<Fragment>()

    private val mTitle = ArrayList<String>()

    override fun initVariableId(): Int = BR.viewModel
    override fun initViewModel(): Class<GankMenuViewModel> = GankMenuViewModel::class.java
    override fun initContentView(
        inflater: LayoutInflater?,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): Int = R.layout.fragment_gank_menu

    override fun initData() {
        super.initData()
        mViewModel?.onGankMenuDataEvent?.observe(this,
            Observer {
                it.forEach { entity ->
                    mTitle.add(entity.title)
                    val fragment = GankListFragment()
                    val bundle = Bundle()
                    bundle.putString("type", entity.type)
                    fragment.arguments = bundle
                    mFragment.add(fragment)
                }
                initAdapter()
            })
    }

    private fun initAdapter() {
        mBinding.layoutMenuViewpager.offscreenPageLimit = 1
        val adapter = BaseFragmentPagerAdapter(activity!!.supportFragmentManager, mFragment, mTitle)
        mBinding.layoutMenuViewpager.adapter = adapter
        mBinding.layoutMenuTab.setupWithViewPager(mBinding.layoutMenuViewpager)
        mBinding.layoutMenuViewpager.addOnPageChangeListener(
            TabLayout.TabLayoutOnPageChangeListener(
                mBinding.layoutMenuTab
            )
        )
    }
}